package cn.leftsite.netty.inaction.transport;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * @author wangjinqiang
 * @date 2019-05-23
 */
public class PlanOioServer {

    public void server(int port) throws IOException {
        final ServerSocket serverSocket = new ServerSocket(port);

        try {
            for (; ; ) {
                final Socket clientSocket = serverSocket.accept();
                System.out.println("Accepted connection from " + clientSocket);

                new Thread(() -> {
                    try (OutputStream out = clientSocket.getOutputStream()) {
                        out.write("Hi\r\n".getBytes(Charset.forName("UTF-8")));
                        out.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            serverSocket.close();
        }
    }
}
